package com.dewod.producesales.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.dewod.producesales.adapter.SnCodeOperaterAdapter;
import com.dewod.producesales.utils.StringUtil;
import com.google.android.material.tabs.TabLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ObjectUtils;
import com.dewod.producesales.R;
import com.dewod.producesales.adapter.CabinetSnAdapter;
import com.dewod.producesales.model.request.SnSubmit;
import com.dewod.producesales.model.request.SnValidate;
import com.dewod.producesales.model.response.PdaInfoVo;
import com.dewod.producesales.model.response.PdaSnStatusVo;
import com.dewod.producesales.model.view.CabinetSn;
import com.dewod.producesales.utils.common.TtsManager;
import com.dewod.producesales.utils.request.RequestApiUtil;
import com.dewod.producesales.viewmodel.SubmitViewModel;
import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 验证页面_快递柜
 */
public class ValidateActivity4Kdg extends AppCompatActivity {

    MyReceiver snNoReceiver = null;

    // 订单号输入框
    private TextInputEditText orderNoInput;

    private RecyclerView cabinetSnRecyclerView;

    private RecyclerView integratedMacRecyclerView;

    private RecyclerView lockCtlBoardRecyclerView;

    // 验证按钮
    private Button verifyButton;

    // 页面数据模型
    private SubmitViewModel viewModel;


    // 柜机SN
    private LinearLayout cabinetSnLayout;

    // 一体机SN
    private LinearLayout integratedMacSnLayout;

    // 锁控板SN
    private LinearLayout lockCtlBoardSnLayout;

    // 柜机渲染适应器
    private CabinetSnAdapter cabinetSnAdapter;

    private SnCodeOperaterAdapter macSnAdapter;

    private SnCodeOperaterAdapter lockSnAdapter;

    // 选项卡容器组件
    private LinearLayout tabContainerLayout;

    // 选项卡组件
    private TabLayout tabLayout;

    private int tabIndex = 0;

    List<View> tabViews = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_validate_kdg);

        // 开启扫码监听
        startScan();

        viewModel = new SubmitViewModel();

        // 初始化控件
        bindViews();

        // 监听数据变化
        observeViewModel();

        // 设置点击事件
        setupClickListeners();

        TtsManager.getInstance().init(this);
    }

    private void bindViews() {
        orderNoInput = findViewById(R.id.orderNo_input);
        cabinetSnRecyclerView = findViewById(R.id.recycler_view_cabinet_sn);
        cabinetSnRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        integratedMacRecyclerView = findViewById(R.id.recycler_view_integratedMac);
        integratedMacRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        lockCtlBoardRecyclerView = findViewById(R.id.recycler_view_lockCtlBoard);
        lockCtlBoardRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        tabContainerLayout = findViewById(R.id.tab_container_layout);
        tabContainerLayout.setVisibility(View.GONE);

        cabinetSnLayout = findViewById(R.id.cabinet_sn_layout);
        cabinetSnLayout.setVisibility(View.VISIBLE);
        integratedMacSnLayout = findViewById(R.id.integratedMac_sn_layout);
        integratedMacSnLayout.setVisibility(View.GONE);
        lockCtlBoardSnLayout = findViewById(R.id.lockCtlBoard_sn_layout);
        lockCtlBoardSnLayout.setVisibility(View.GONE);

        verifyButton = findViewById(R.id.verify_button);

        tabLayout = findViewById(R.id.tab_layout);

        // 添加 Tab
        tabViews.add(cabinetSnLayout);
        tabViews.add(integratedMacSnLayout);
        tabViews.add(lockCtlBoardSnLayout);

        // 禁用键盘输入
        disableEditTextInput(orderNoInput);
    }

    private void observeViewModel() {
        viewModel.orderNo.observe(this, s -> {
            orderNoInput.setText(s);
            if(macSnAdapter != null ) macSnAdapter.setOrderNo(s);
            if(lockSnAdapter!= null ) lockSnAdapter.setOrderNo(s);
        });

        viewModel.validated.observe(this, visible -> {
            verifyButton.setVisibility(visible ? View.GONE : View.VISIBLE);
        });

        viewModel.allChecked.observe(this, checked -> {
//            snInputLayout.setVisibility(checked ? View.VISIBLE : View.GONE);
        });

        viewModel.cabinetSnList.observe(this, cabinetSns -> {
            if(cabinetSns == null || cabinetSns.isEmpty()){
                tabContainerLayout.setVisibility(View.GONE);
            }else{
                tabContainerLayout.setVisibility(View.VISIBLE);
                if(cabinetSnAdapter == null ){
                    cabinetSnAdapter = new CabinetSnAdapter(cabinetSns);
                    cabinetSnRecyclerView.setAdapter(cabinetSnAdapter);
                }else{
                    cabinetSnAdapter.updateData(cabinetSns);
                }
                viewModel.checkIsAllChecked();
            }
        });

        macSnAdapter = new SnCodeOperaterAdapter(viewModel, new ArrayList<>());
        integratedMacRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        integratedMacRecyclerView.setAdapter(macSnAdapter);

        viewModel.macSnList.observe(this, snList -> {
            Log.i("viewModel.macSnList.observe", JSON.toJSONString(snList));
            macSnAdapter.updateData(snList,2);
        });

        lockSnAdapter = new SnCodeOperaterAdapter(viewModel, new ArrayList<>());
        lockCtlBoardRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        lockCtlBoardRecyclerView.setAdapter(lockSnAdapter);

        viewModel.lockSnList.observe(this, snList -> {
            lockSnAdapter.updateData(snList, 3);
        });

        viewModel.toastMessage.observe(this, message -> {
            if (message != null) {
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                this.speak(message);
            }
        });

    }

    private void setupClickListeners() {
        findViewById(R.id.verify_button).setOnClickListener(v -> this.validateOrderNo(viewModel.orderNo.getValue()));

        findViewById(R.id.submit_button).setOnClickListener(v -> this.submitForm());

        findViewById(R.id.clear_button).setOnClickListener(v -> {
            // 交互确认清空
            new android.app.AlertDialog.Builder(this)
                    .setTitle("确认操作")
                    .setMessage("确定要清空所有输入内容吗？")
                    .setPositiveButton("确定", (dialog, which) -> viewModel.clearAll())
                    .setNegativeButton("取消", null)
                    .show();
        });

        findViewById(R.id.cancel_button).setOnClickListener(v -> {
            new android.app.AlertDialog.Builder(this)
                    .setTitle("确认操作")
                    .setMessage("确定取消订单操作吗？")
                    .setPositiveButton("确定", (dialog, which) -> this.cancel())
                    .setNegativeButton("取消", null)
                    .show();
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabIndex = tab.getPosition();
                showTab(tabIndex);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void cancel() {
        RequestApiUtil.cancel(new SnSubmit(viewModel), responseData -> {
            if(responseData.getSuccess()){
                viewModel.showToast("取消成功");
                viewModel.clearAll();
            }else{
                viewModel.showToast(responseData.getMessage());
            }
        });
    }

    private void showTab(int index){
        for (int i = 0; i < tabViews.size(); i++){
            tabViews.get(i).setVisibility(i == index ? View.VISIBLE : View.GONE);
        }
    }

    /**
     *  整个表单提交
     */
    private void submitForm() {
        // 提交逻辑
        RequestApiUtil.formSubmit(new SnSubmit(viewModel), responseData -> {
            if(responseData.getSuccess()){
                viewModel.showToast("操作成功");
                viewModel.clearAll();
            }else{
                viewModel.showToast(responseData.getMessage());
            }
        });
    }

    // 合同单号校验
    private void validateOrderNo(String barcode){
        if (TextUtils.isEmpty(barcode)) {
            viewModel.showToast("未扫描订单码");
            return;
        }

        SnValidate form = new SnValidate(barcode,barcode,0);
        RequestApiUtil.validateOrderNo(form, responseData -> {
            Log.i("validateOrderNo","validateSn responseData:" + JSON.toJSONString(responseData) );
            this.runOnUiThread(() -> {
                if(responseData.getSuccess()){
                    viewModel.validated.setValue(true);
                    Toast.makeText(this, "订单号验证通过", Toast.LENGTH_SHORT).show();
                    PdaInfoVo info = JSON.parseObject(JSON.toJSONString(responseData.getData()), PdaInfoVo.class );

                    System.out.println( JSON.toJSONString(info));
                    // 展示柜体SN
                    List<PdaSnStatusVo> suppliers = info.getSuppliers();

                    List<CabinetSn> list = new ArrayList<>();
                    // 写入柜体SN数据 , 不会为空
                    if(ObjectUtils.isNotEmpty( suppliers)){
                        suppliers.forEach(item -> {
                            list.add(new CabinetSn(item));
                        });
                        viewModel.cabinetSnList.postValue(list);
                    }else{
                        viewModel.orderNo.setValue(null);
                        viewModel.showToast("订单未关联柜机，请检查销售合同");
                    }

                    // 写入集成一体机数据
                    List<PdaSnStatusVo> machines = info.getMachine();
                    if(ObjectUtils.isNotEmpty( machines)){
                        machines.forEach(item -> viewModel.updateIntegratedMacSn(item.getSn()));
                    }

                    // 写入锁控板数据
                    List<PdaSnStatusVo> locks = info.getLocks();
                    if(ObjectUtils.isNotEmpty( locks)){
                        locks.forEach(item -> viewModel.updateLockCtlBoardSn(item.getSn()));
                    }
                }else {
                    viewModel.orderNo.setValue(null);
                    String msg = responseData.getMessage();
                    viewModel.showToast(msg);
                    Toast.makeText(this, "验证失败 " + msg, Toast.LENGTH_SHORT).show();
                }
            });
        });
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void startScan() {
        if(snNoReceiver == null){
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.scanservice.action.UPLOAD_BARCODE_DATA");
            snNoReceiver = new MyReceiver();
            registerReceiver(snNoReceiver, filter);
        }
    }


    /**
     * 禁用键盘输入
     * @param editText
     */
    private void disableEditTextInput(EditText editText) {
        editText.setKeyListener(null);
        editText.setFocusable(true);
        editText.setClickable(true);
    }


    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("action:" + action);
            if (TextUtils.equals("android.scanservice.action.UPLOAD_BARCODE_DATA", action)) {
                String barcodeStr = intent.getStringExtra("barcode");
                Log.i("SCAN","UPLOAD_BARCODE_DATA barcodeStr:" + barcodeStr);
                String finalBarcodeStr = StringUtil.trimAll(barcodeStr);
                Log.i("SCAN","UPLOAD_BARCODE_DATA finalBarcodeStr:" + finalBarcodeStr);
                // 扫描到二维码，处理数据
                if(Boolean.FALSE.equals(viewModel.validated.getValue())){ //  未验证成功，只更新订单号
                    viewModel.updateOrderNo(finalBarcodeStr);
                } else {
                    if(tabIndex == 0 ){
                        List<CabinetSn> sns = viewModel.cabinetSnList.getValue();
                        assert sns != null;
                        CabinetSn sn = sns.stream()
                                .filter(Objects::nonNull)
                                .filter(csn -> csn.getSn().equals(finalBarcodeStr))
                                .findFirst()
                                .orElse(null);

                        if(sn != null ){
                            if(!sn.getChecked()){
                                // 发送到服务端校验
                                validateSnNo(finalBarcodeStr,1);
                            }else{
                                viewModel.showToast("该柜机码已扫描");
                            }
                        }else{
                            viewModel.showToast("该条码与订单无关");
                        }
                    }else if(tabIndex == 1 ){
                        if(viewModel.getSn(viewModel.macSnList.getValue(),finalBarcodeStr) == null){
                            validateSnNo(finalBarcodeStr,2);
                        }else{
                            viewModel.showSnDuplicateToast();
                        }
                    }else if(tabIndex == 2){
                        if(viewModel.getSn(viewModel.lockSnList.getValue(),finalBarcodeStr) == null){
                            validateSnNo(finalBarcodeStr,3);
                        }else{
                            viewModel.showSnDuplicateToast();
                        }
                    }
                }
            } else {
//                speak("不是我们的二维码");
            }
        }

    }


    private void validateSnNo(String barcode , Integer type){
        SnValidate form = new SnValidate(viewModel.orderNo.getValue(),barcode,type);
        RequestApiUtil.validateSn(form, responseData -> {
            System.out.println("validateSn responseData:" + JSON.toJSONString(responseData));
            this.runOnUiThread(() -> {
                if(responseData.getSuccess()){
                    if(type == 1 ){
                        viewModel.setCabinetSnChecked(barcode);
                    }else if(type == 2){
                        viewModel.updateIntegratedMacSn(barcode);
                    }else if(type == 3) {
                        viewModel.updateLockCtlBoardSn(barcode);
                    }
                    Toast.makeText(this, "验证通过", Toast.LENGTH_SHORT).show();
                }else {
                    String msg = responseData.getMessage();
                    viewModel.showToast(msg);
                    Toast.makeText(this, "验证失败 " + msg, Toast.LENGTH_SHORT).show();
                }
            });
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopScan();
        TtsManager.getInstance().release();
    }

    private void stopScan() {
        if(snNoReceiver != null){
            unregisterReceiver(snNoReceiver);
        }
    }

    protected void speak(String msg) {
        if (TtsManager.getInstance() == null ) {
            Toast.makeText(this, "语音引擎初始化失败", Toast.LENGTH_SHORT).show();
        } else {
            TtsManager.getInstance().speakText(msg);
        }
    }
}